package com.woniuxy.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@ControllerAdvice("com.woniuxy.controller")
public class GlobalException {
    @ExceptionHandler(Exception.class) // 管理的异常类型
    public void handlerException(HttpServletResponse response, Exception e) throws IOException {
        e.printStackTrace();
//        System.out.println("全局异常处理生效");
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",500);
        map.put("msg","请联系管理员");
        //前后台传输的是json格式数据
        //以前使用response向前台输出数据 文本形式 text/html;charset=utf-8
        response.setContentType("application/json;charset=utf-8");
        try{
            //json字符串 jackxon包中的类，这个类可以将对象转换成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(map);
            response.getWriter().write(s);
        } catch (IOException ex){
            throw new RuntimeException(ex);
        }

    }
}
